<template>
  <va-modal v-model="isVisible" hide-default-actions title="上传表情包">
    <div class="upload-container">
      <va-alert v-if="!isAuthenticated" color="warning" icon="warning">
        请先登录后再上传表情包
      </va-alert>
      
      <template v-if="isAuthenticated">
        <va-alert v-if="message.text" :color="message.type" icon="info">
          {{ message.text }}
        </va-alert>
        
        <form @submit.prevent="handleUpload" class="upload-form">
          <va-input
            v-model="title"
            label="表情包标题"
            class="mb-4"
            placeholder="给你的表情包取个名字"
            :error="!!titleError"
            :error-messages="titleError"
            @update:modelValue="titleError = ''"
            required
          />
          
          <div class="file-upload-wrapper mb-4">
            <label class="file-upload-label">
              <input 
                type="file" 
                accept="image/*" 
                @change="handleFileChange" 
                class="file-input"
              />
              <va-button 
                type="button" 
                color="secondary" 
                icon="cloud_upload" 
                class="upload-button"
              >
                选择图片
              </va-button>
              <span class="file-name">{{ fileName || '未选择文件' }}</span>
            </label>
            <p v-if="fileError" class="error-message">{{ fileError }}</p>
          </div>
          
          <va-input
            v-model="tags"
            label="标签（用逗号分隔）"
            class="mb-4"
            placeholder="例如：搞笑,动画,表情"
            @update:modelValue="tagsError = ''"
            :error="!!tagsError"
            :error-messages="tagsError"
          />
          
          <div class="preview-container mb-4" v-if="previewUrl">
            <h4>预览</h4>
            <img :src="previewUrl" alt="预览" class="preview-image" />
          </div>
          
          <div class="actions">
            <va-button type="submit" color="primary" :loading="isLoading">
              上传
            </va-button>
            <va-button @click="closeDialog" flat>
              取消
            </va-button>
          </div>
        </form>
      </template>
    </div>
  </va-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAuth } from '../composables/useAuth'
import { uploadMeme } from '../api/memes'
import { syncTags } from '../api/uploads'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'upload-success'])

const { isAuthenticated } = useAuth()

const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const title = ref('')
const tags = ref('')
const file = ref(null)
const fileName = ref('')
const previewUrl = ref('')
const isLoading = ref(false)
const titleError = ref('')
const tagsError = ref('')
const fileError = ref('')
const message = ref({ text: '', type: 'info' })

watch(() => props.modelValue, (newVal) => {
  // Reset form when dialog opens
  if (newVal) {
    resetForm()
  }
})

const handleFileChange = (event) => {
  const selectedFile = event.target.files[0]
  if (!selectedFile) return
  
  fileError.value = ''
  
  // Check file type
  if (!selectedFile.type.startsWith('image/')) {
    fileError.value = '请选择图片文件'
    return
  }
  
  // Check file size (max 5MB)
  if (selectedFile.size > 5 * 1024 * 1024) {
    fileError.value = '文件大小不能超过5MB'
    return
  }
  
  file.value = selectedFile
  fileName.value = selectedFile.name
  
  // Create preview
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(selectedFile)
}

const handleUpload = async () => {
  // Validate
  let isValid = true
  
  if (!title.value) {
    titleError.value = '请输入表情包标题'
    isValid = false
  }
  
  if (!file.value) {
    fileError.value = '请选择要上传的图片'
    isValid = false
  }
  
  if (!isValid) return
  
  isLoading.value = true
  message.value = { text: '', type: 'info' }
  
  try {
    const formData = new FormData()
    formData.append('title', title.value)
    formData.append('file', file.value)
    
    if (tags.value) {
      const tagsArray = tags.value.split(',').map(tag => tag.trim())
      formData.append('tags', JSON.stringify(tagsArray))
    }
    
    const response = await uploadMeme(formData)
    
    // 上传成功后同步标签数据
    try {
      await syncTags()
      message.value = { text: '上传成功！标签已同步', type: 'success' }
    } catch (syncError) {
      console.error('标签同步失败:', syncError)
      message.value = { text: '上传成功！但标签同步失败', type: 'success' }
    }
    
    // Reset form after successful upload
    setTimeout(() => {
      closeDialog()
      emit('upload-success', response.data)
    }, 1500)
  } catch (error) {
    message.value = { text: '上传失败，请重试', type: 'danger' }
  } finally {
    isLoading.value = false
  }
}

const resetForm = () => {
  title.value = ''
  tags.value = ''
  file.value = null
  fileName.value = ''
  previewUrl.value = ''
  titleError.value = ''
  tagsError.value = ''
  fileError.value = ''
  message.value = { text: '', type: 'info' }
}

const closeDialog = () => {
  isVisible.value = false
}
</script>

<style scoped>
.upload-container {
  padding: 1rem 0;
}

.mb-4 {
  margin-bottom: 1rem;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.file-upload-wrapper {
  margin-bottom: 1rem;
}

.file-upload-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.file-input {
  display: none;
}

.file-name {
  margin-left: 0.5rem;
  color: var(--text-secondary);
}

.error-message {
  color: #f44336;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

.preview-container {
  margin-top: 1rem;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  margin-top: 0.5rem;
  border-radius: 0.25rem;
  border: 1px solid var(--border-color);
}
</style> 